package com.wenzhoujie.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDResourcesUtil;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.lingou.www.R.color;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.HomeSearchActivity;
import com.wenzhoujie.MainActivity;
import com.wenzhoujie.MapSearchActivity;
import com.wenzhoujie.ShopCartActivity;
import com.wenzhoujie.SuperMarketSubCateActivity;
import com.wenzhoujie.SuperMarketSubCateItemsActivity;
import com.wenzhoujie.adapter.CategoryCateLeftAdapter;
import com.wenzhoujie.adapter.CategoryCateRightAdapter;
import com.wenzhoujie.adapter.CategoryOrderAdapter;
import com.wenzhoujie.adapter.CategoryQuanLeftAdapterNew;
import com.wenzhoujie.adapter.CategoryQuanRightAdapterNew;
import com.wenzhoujie.adapter.MerchantListAdapter;
import com.wenzhoujie.adapter.smCategoryCateLeftAdapter;
import com.wenzhoujie.adapter.smCategoryCateRightAdapter;
import com.wenzhoujie.adapter.smSubCateListAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.baidumap.BaiduMapManager;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeName;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeValue;
import com.wenzhoujie.constant.Constant.SearchTypeMap;
import com.wenzhoujie.constant.Constant.SearchTypeNormal;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.SD2LvCategoryView;
import com.wenzhoujie.customview.SDBottomNavigatorBaseItem;
import com.wenzhoujie.customview.SDLvCategoryView;
import com.wenzhoujie.customview.SDLvCategoryView.SDLvCategoryViewListener;
import com.wenzhoujie.customview.smSD2LvCategoryView;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.Bcate_listBcate_typeModel;
import com.wenzhoujie.model.Bcate_listModel;
import com.wenzhoujie.model.CategoryOrderModel;
import com.wenzhoujie.model.MerchantlistActItemModel;
import com.wenzhoujie.model.Quan_listModel;
import com.wenzhoujie.model.Quan_listQuan_subModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.smGoodsCates;
import com.wenzhoujie.model.smSmallCates;
import com.wenzhoujie.model.smSubCateItemModel;
import com.wenzhoujie.model.smSubCateListModel;
import com.wenzhoujie.model.act.MerchantlistActModel;
import com.wenzhoujie.model.act.smCateslistActModel;
import com.wenzhoujie.model.act.smSubCatelistActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDViewNavigatorManager;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

public class SuperMarketSubCateFragment extends BaseFragment implements OnClickListener
{
	// 超市id 
	public static final String EXTRA_BRAND_ID = "extra_brand_id";
	//超市名稱
	public static final String EXTRA_TITLE_TXT = "extra_title_txt";
	//一級分類id
		public static final String EXTRA_CATE_ID = "extra_cate_id";
	//一級分類名稱
	public static final String EXTRA_CATE_NAME = "extra_cate_name";
	
	public static final String EXTRA_FROM_TXT = "extra_from_txt";
	
	public static final String EXTRA_CATE_TYPE_ID = "extra_cate_type_id";
	
	//public static final String TITILE_NAME = "title_name";
	//public static final String EXTRA_KEY_WORD = "extra_key_word";
	

	@ViewInject(id = R.id.frag_msm_cate_name)
	private TextView mTvName = null;

	@ViewInject(id = R.id.frag_msm_list_cv_right)
	private smSD2LvCategoryView mCvRight = null;
	//private ImageView cateMenu = null;

	@ViewInject(id = R.id.frag_msm_list_ll_empty)
	private LinearLayout mLlEmpty = null;

	@ViewInject(id = R.id.frag_msm_list_ptrlv_content)
	private ListView mPtrlvContent = null;

	private smSubCateListAdapter mAdapter = null;
	private List<smSubCateItemModel> mListModel = new ArrayList<smSubCateItemModel>();
	private SDViewNavigatorManager mViewManager = new SDViewNavigatorManager();

	private boolean isFirstBindCategoryViewData = true;

	// --------搜索条件-----
	// private SearchConditionModel mSearcher = new SearchConditionModel();

	private int pageTotal;
	// =======================提交到服务器参数
	private String title_name;

	private String quan_id;
	
	/** 一级分类id */
	private String cate_id;
	/** 商家id */
	private String brand_id;
	//private int page;
	/** 二级分类id */
	private String cata_type_id;
	private String order_type;
	/** 是否加载支持自主下单功能的商家1:是，0:否 */
	private String is_auto_order;
	
	/** 来自哪里的点击 */
	private String from_txt;

	private String title_txt;
	private String cata_type_name;
	
	private PopupWindow pop;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_merchant_supermarket_subcate, container, false);
		view = setmTitleType(TitleType.TITLE_SIMPLE, view);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		getIntentData();
		initTitle();
		bindDefaultLvData();
		initCategoryView();
		initCategoryViewNavigatorManager();
		registeClick();
		requestData(false);
		requestMenu();
	}


	private void initTitle()
	{

		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				
					//mFragWebview.startLoadData();
					//finish();
				gotocart();
		
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
					finish();
			}
		});
		//mTitleSimple.setRightText("刷新");
		//mTitleSimple.setRightText("");
		mTitleSimple.setRightImage(R.drawable.ic_shopcart_new);

		if (title_txt != null)
		{
			mTitleSimple.setTitleTop(title_txt);
		}
		
	}

	private void gotocart()
	{
		this.getActivity().startActivity(new Intent(this.getActivity(), ShopCartActivity.class));
	}
	
	private void finish()
	{
		this.getActivity().finish();
	}
	
	public String getNowCateId()
	{
		return cate_id;
	}
	public String getNowSmId()
	{
		return brand_id;
	}
	public String getNowSmName()
	{
		return title_txt;
	}

	private void getIntentData()
	{
		from_txt = "";

		brand_id = getActivity().getIntent().getStringExtra(EXTRA_BRAND_ID);
		cate_id = getActivity().getIntent().getStringExtra(EXTRA_CATE_ID);
		//title_name = getActivity().getIntent().getStringExtra(TITILE_NAME);
		
		from_txt = getActivity().getIntent().getStringExtra(EXTRA_FROM_TXT);
		
		title_txt = getActivity().getIntent().getStringExtra(EXTRA_TITLE_TXT);
		title_name = title_txt;
		cata_type_name = getActivity().getIntent().getStringExtra(EXTRA_CATE_NAME);
		mTvName.setText(cata_type_name);
		cata_type_id = getActivity().getIntent().getStringExtra(EXTRA_CATE_TYPE_ID);
		
	}

	private void bindDefaultLvData()
	{
		mAdapter = new smSubCateListAdapter(mListModel, getActivity());
		mPtrlvContent.setAdapter(mAdapter);
	}

	private void initCategoryViewNavigatorManager()
	{
		SDBottomNavigatorBaseItem[] items = new SDBottomNavigatorBaseItem[] {  mCvRight };
		mViewManager.setItems(items);
		mViewManager.setmMode(SDViewNavigatorManager.Mode.CAN_NONE_SELECT);
	}

	private void initCategoryView()
	{//菜單
		//mCvRight.setmBackgroundNormal(R.drawable.bg_choosebar_press_down);
		//mCvRight.setmBackgroundSelect(R.drawable.bg_choosebar_press_up);
		//mCvRight.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		//mCvRight.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvRight.setmListener(new smSD2LvCategoryView.SD2LvCategoryViewListener()
		{

			@Override
			public void onRightItemSelect(int leftIndex, int rightIndex, Object leftModel, Object rightModel)
			{//二級分類
				smGoodsCates left = (smGoodsCates) leftModel;
				smSmallCates right = (smSmallCates) rightModel;
				//cate_id = left.getId();
				
				//cata_type_id = right.getId();
				//mPtrlvContent.setRefreshing();
				//cata_type_name=left.getName();
				
				//這裡要做超市二级分类More
				Intent intent = new Intent(App.getApplication(), SuperMarketSubCateItemsActivity.class);
				//intent.putExtra(SuperMarketSubCateFragment.EXTRA_BRAND_ID, brand_id); //sm id
				//intent.putExtra(SuperMarketSubCateFragment.EXTRA_TITLE_TXT,title_txt); //sm name
				//intent.putExtra(SuperMarketSubCateFragment.EXTRA_CATE_ID, left.getId()); 
				//intent.putExtra(SuperMarketSubCateFragment.EXTRA_CATE_NAME, left.getName());
				intent.putExtra(SuperMarketSubCateItemsActivity.EXTRA_MERCHANT_ID, brand_id);
				intent.putExtra(SuperMarketSubCateItemsActivity.EXTRA_MERCHANT_TITLE, title_txt);
				intent.putExtra(SuperMarketSubCateItemsActivity.EXTRA_CATE_ID,left.getId());
				intent.putExtra(SuperMarketSubCateItemsActivity.EXTRA_SUBCATE_ID, right.getId());
				intent.putExtra(SuperMarketSubCateItemsActivity.EXTRA_SUBCATE_NAME, right.getName() );
				//子分類id
				startActivity(intent);
			}

			@Override
			public void onLeftItemSelect(int leftIndex, Object leftModel, boolean isNotifyDirect)
			{//一級分類
				if (isNotifyDirect)
				{
					smGoodsCates left = (smGoodsCates) leftModel;
					smSmallCates right = left.getSub_cate().get(0);
					cate_id = left.getId();
					cata_type_id = right.getId();
					
					//mPtrlvContent.setRefreshing();
					//cata_type_name=null;
					//重新打開本頁面
//					Intent intent = new Intent(App.getApplication(), SuperMarketSubCateActivity.class);
//					intent.putExtra(SuperMarketSubCateFragment.EXTRA_BRAND_ID, brand_id); //sm id
//					intent.putExtra(SuperMarketSubCateFragment.EXTRA_TITLE_TXT,title_txt); //sm name
//					intent.putExtra(SuperMarketSubCateFragment.EXTRA_CATE_ID, left.getId()); 
//					intent.putExtra(SuperMarketSubCateFragment.EXTRA_CATE_NAME, left.getName()); 
//					
//					startActivity(intent);
				}
			}
		});

		
//		List<CategoryOrderModel> listOrderModel = new ArrayList<CategoryOrderModel>();
//		CategoryOrderModel orderModelDefault = new CategoryOrderModel();
//		orderModelDefault.setName(CategoryOrderTypeName.DEFAULT);
//		orderModelDefault.setValue(CategoryOrderTypeValue.DEFAULT);
//		listOrderModel.add(orderModelDefault);

		
		/*
		 * CategoryOrderModel orderModelNewest = new CategoryOrderModel();
		 * orderModelNewest.setName(CategoryOrderTypeName.NEWEST);
		 * orderModelNewest.setValue(CategoryOrderTypeValue.NEWEST);
		 * listOrderModel.add(orderModelNewest);
		 * 
		 * CategoryOrderModel orderModelBuyCount = new CategoryOrderModel();
		 * orderModelBuyCount.setName(CategoryOrderTypeName.BUY_COUNT);
		 * orderModelBuyCount.setValue(CategoryOrderTypeValue.BUY_COUNT);
		 * listOrderModel.add(orderModelBuyCount);
		 * 
		 * CategoryOrderModel orderModelPriceAsc = new CategoryOrderModel();
		 * orderModelPriceAsc.setName(CategoryOrderTypeName.PRICE_ASC);
		 * orderModelPriceAsc.setValue(CategoryOrderTypeValue.PRICE_ASC);
		 * listOrderModel.add(orderModelPriceAsc);
		 * 
		 * CategoryOrderModel orderModelPriceDesc = new CategoryOrderModel();
		 * orderModelPriceDesc.setName(CategoryOrderTypeName.PRICE_DESC);
		 * orderModelPriceDesc.setValue(CategoryOrderTypeValue.PRICE_DESC);
		 * listOrderModel.add(orderModelPriceDesc);
		 */
		//CategoryOrderAdapter adapter = new CategoryOrderAdapter(listOrderModel, getActivity());
		//mCvRight.setAdapter(adapter);

	}

	private void requestData(final boolean isLoadMore)
	{
		RequestModel model = new RequestModel();
		model.put("act", "chaoshi_sub_cate");
		//model.put("keyword", keyword);
		//model.put("m_latitude", BaiduMapManager.getInstance().getLatitude());
		//model.put("m_longitude", BaiduMapManager.getInstance().getLongitude());
		//model.put("order_type", order_type); // 排序类型
		//model.put("cata_type_id", cata_type_id);// 小分类ID
		model.put("cate_id", cate_id);// 大分类ID
		model.put("id", brand_id);//商家id
		//model.put("city_id", AppRuntimeWorker.getCity_id());
		//model.put("quan_id", quan_id);
		//model.put("page", page);
		//model.put("from", from_txt);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				//System.out.println("cate_id:"+cate_id+"+"+responseInfo.result);
				smSubCatelistActModel actModel = JsonUtil.json2Object(responseInfo.result, smSubCatelistActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						
//						if (actModel.getPage() != null)
//						{
//							page = actModel.getPage().getPage();
//							pageTotal = actModel.getPage().getPage_total();
//						}
						SDViewUtil.updateAdapterByList(mListModel, actModel.getCate_items(), mAdapter, isLoadMore);
					}
				}
				//然後獲取菜單分類
				//requestMenu();
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				dealFinishRequest();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	protected void dealFinishRequest()
	{
		AppHelper.hideLoadingDialog();
		SDViewUtil.toggleEmptyMsgByList(mListModel, mLlEmpty);
	}
	
	private void requestMenu()
	{
		RequestModel model = new RequestModel();
		model.put("act", "get_shop_cate");
		//model.put("keyword", keyword);
		//model.put("m_latitude", BaiduMapManager.getInstance().getLatitude());
		//model.put("m_longitude", BaiduMapManager.getInstance().getLongitude());
		//model.put("order_type", order_type); // 排序类型
		//model.put("cata_type_id", cata_type_id);// 小分类ID
		//model.put("cate_id", cate_id);// 大分类ID
		model.put("id", brand_id);//商家id
		model.put("supplier_id", brand_id);
		//model.put("city_id", AppRuntimeWorker.getCity_id());
		//model.put("quan_id", quan_id);
		//model.put("page", page);
		//model.put("from", from_txt);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				//AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{System.out.println(responseInfo.result);
				smCateslistActModel actModel = JsonUtil.json2Object(responseInfo.result, smCateslistActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						if (isFirstBindCategoryViewData)
						{
							bindCategoryViewData(actModel.getCate_list());
							
							isFirstBindCategoryViewData = false;
						}

					}
				}
			
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
	
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}


	private void bindCategoryViewData(List<smGoodsCates> listModel)
	{
		if (listModel != null && listModel.size() > 0)
		{
			smGoodsCates leftModel = listModel.get(0);
			if (leftModel != null)
			{
				List<smSmallCates> listRight = leftModel.getSub_cate();

				smCategoryCateLeftAdapter adapterLeft = new smCategoryCateLeftAdapter(listModel, getActivity());
				//adapterLeft.setDefaultSelectId(cate_id);

				smCategoryCateRightAdapter adapterRight = new smCategoryCateRightAdapter(listRight, getActivity());

				mCvRight.setLeftAdapter(adapterLeft);
				mCvRight.setRightAdapter(adapterRight);
				mCvRight.setAdapterFinish();
				
				/*cata_type_id = cate_id;*/
				//mPtrlvContent.setRefreshing();
			}
		}
	}

	

	private void registeClick()
	{
		//mIvLocation.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{

		case R.id.frag_merchant_list_tv_location:
			//clickTv_locaiton();
			break;

		default:
			break;
		}
	}

	private void clickTv_locaiton()
	{
		
	}



	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt()))
		{
//		case CITY_CHANGE:
//			initTitle();
//			mPtrlvContent.setRefreshing();
//			break;

		default:
			break;
		}
	}

}